package jp.co.sharp.android.parents.kidsguard.activity.bluetooth;

import android.app.Activity;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONObject;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.common.MimamoriBusinessService;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothItemDto;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.activity.profile.ProfileEditActivity;

/**
 * ペアリング認証
 */
public class BluetoothPairingActivity extends Activity {

    private static final int DISCONNECT_BLUETOOTH = 0;
    private static final int PAIRE_BLUETOOTH = 1;
    private static final int UNPAIRE_BLUETOOTH = 2;

    private BluetoothItemDto mAddBluetoothItemDto;
    public ParentBleTransfer mParentBleTransfer;
    private boolean mUnReceiver = false;
    private static final String TAG = "TAG";
    private String mAction;
    private MimamoriBusinessService mMimamoriBusinessService;
    private App mApp;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(this.TAG, "BluetoothPairingActivity_onCreate");
        setContentView(R.layout.activity_bluetooth_pairing);

        mApp = (App)getApplication();
        initReceiver();
        initActivity();
        mMimamoriBusinessService = new MimamoriBusinessService(BluetoothPairingActivity.this,
                mApp, new Intent(getIntent()), (NotificationManager)getSystemService(NOTIFICATION_SERVICE));
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "BluetoothPairingActivity_onStart");
        synchronized (mSyncLock) {
            mMimamoriBusinessService.registerReceiver();
            mUnReceiver = false;
            mApp.setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(this.TAG, "BluetoothPairingActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        mMimamoriBusinessService.unRegisterSystemReceiver();
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                try {
                    mMimamoriBusinessService.unRegisterReceiver();
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(this.TAG, "BluetoothPairingActivity_onDestroy");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        mMimamoriBusinessService.unRegisterSystemReceiver();
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                try {
                    mMimamoriBusinessService.unRegisterReceiver();
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                mUnReceiver = true;
            }
        }
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(this.TAG, "BluetoothPairingActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        this.mParentBleTransfer = ((App)getApplication()).getmParentBleTransfer();
    }

    /**
     * 初期化Activity
     */
    private void initActivity() {
        Log.i(this.TAG, "BluetoothPairingActivity_initActivity");
        Intent intent = getIntent();
        mAction = intent.getAction();
        mAddBluetoothItemDto = (BluetoothItemDto)intent.getSerializableExtra(Constants.KEY_ADD_BLUETOOTH);
        new BusinessThread(PAIRE_BLUETOOTH, mAddBluetoothItemDto).start();
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        Log.i(this.TAG, "BluetoothPairingActivity_backActivity");

        if (checkBluetoothState()) {
            // ページジャンプ
            mPageJumpFlag = true;
            new BusinessThread(UNPAIRE_BLUETOOTH, mAddBluetoothItemDto).start();
        } else {
            OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(BluetoothPairingActivity.this, R.style.commonDlg);
            openBluetoothConfirmDlg.show();
            openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    openBluetoothConfirmDlg.dismiss();
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                }
            });
        }
    }

    /**
     *  処理スレッド
     */
    private class BusinessThread extends Thread {
        private int mBusinessFlag = 0;
        private BluetoothItemDto mBluetoothItemDto;

        public BusinessThread(int pBusinessFlag, BluetoothItemDto pBluetoothItemDto) {
            this.mBusinessFlag = pBusinessFlag;
            this.mBluetoothItemDto = pBluetoothItemDto;
        }

        @Override
        public void run() {
            try {
                switch (mBusinessFlag) {
                    case DISCONNECT_BLUETOOTH:
                        disconnectBluetooth(mBluetoothItemDto);
                        Intent intent1 = new Intent();
                        if (null != mAction) {
                            intent1.setAction(mAction);
                        }
                        intent1.setClass(BluetoothPairingActivity.this, BluetoothSearchActivity.class);
                        startActivity(intent1);
                        break;
                    case PAIRE_BLUETOOTH:
                        pairBluetooth(mBluetoothItemDto);
                        break;
                    case UNPAIRE_BLUETOOTH:
                        unPairBluetooth(mBluetoothItemDto);
                        new BusinessThread(DISCONNECT_BLUETOOTH, mAddBluetoothItemDto).start();
                        break;
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    /**
     * ペアリングをリクエスト
     * @param pBluetoothItemDto
     */
    private void pairBluetooth(BluetoothItemDto pBluetoothItemDto) {
        try {
            Log.i(this.TAG, "BluetoothPairingActivity_pairBluetooth");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_REQUEST_PIN);
            jsonObject.put("data", JSONObject.NULL);

            mParentBleTransfer.writeLeData(pBluetoothItemDto.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(this.TAG, e.getMessage());
        }
    }

    /**
     * ペア解除
     * @param pBluetoothItemDto
     */
    private void unPairBluetooth(BluetoothItemDto pBluetoothItemDto) {
        try {
            Log.i(this.TAG, "BluetoothPairingActivity_pairBluetooth");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_CANCEL_PIN);
            jsonObject.put("data", JSONObject.NULL);

            mParentBleTransfer.writeLeData(pBluetoothItemDto.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(this.TAG, e.getMessage());
        }
    }

    /**
     * 接続解除
     * @param pBluetoothItemDto
     */
    private void disconnectBluetooth(BluetoothItemDto pBluetoothItemDto) {
        Log.i(TAG, "BluetoothPairingActivity_disconnectBluetooth");
        this.mParentBleTransfer.disconnectLeDevice(pBluetoothItemDto.getMacAddress());
    }

    /**
     * bluetooth status
     * @return true: Open  false: Close
     */
    private boolean checkBluetoothState() {
        Log.i(this.TAG, "BluetoothPairingActivity_checkBluetoothState");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (bluetoothAdapter.isEnabled()) {
                return true;
            }
        }
        return false;
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {

                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);

                    if (RequestMethodConstants.METHOD_PIN_BLUETOOTH_SUCCESS.equals(jsonObject.getString("method"))) {
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setClass(BluetoothPairingActivity.this, ProfileEditActivity.class);
                        intent1.setAction(mAction);
                        intent1.putExtra(Constants.KEY_ADD_BLUETOOTH, mAddBluetoothItemDto);
                        startActivity(intent1);
                    } else if (RequestMethodConstants.METHOD_PIN_BLUETOOTH_CANCEL.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイからペアリング要求がキャンセルされました";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(BluetoothPairingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                new BusinessThread(DISCONNECT_BLUETOOTH, mAddBluetoothItemDto).start();
                                processWarringDlg.dismiss();
                            }
                        });
                    } else if (RequestMethodConstants.METHOD_CANCEL_PIN.equals(jsonObject.getString("method"))) {
//                        new BusinessThread(DISCONNECT_BLUETOOTH, mAddBluetoothItemDto).start();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化 TODO
//                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
//                    Intent intent1 = new Intent();
//                    if (null != mAction) {
//                        intent1.setAction(mAction);
//                    }
//                    intent1.setClass(BluetoothPairingActivity.this, BluetoothSearchActivity.class);
//                    startActivity(intent1);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
}
